<template>
  <div class="classify" ref="wrapper">
    <div class="content">
      <ul>
        <li
          class="classify_son"
          v-for="item of classify"
          :key="item.id"
          @click="classifyClick(item.id)"
        >
          <p><span class="act" :class="{active : current === item.id }">{{item.name}}</span></p>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import 'swiper/dist/css/swiper.min.css'
import BScroll from 'better-scroll'
export default {
  name: 'HomeSwiper',
  data () {
    return {
      scroll: null,
      current: 0,
      classify: [
        {
          name: '比萨',
          id: 0
        },
        {
          name: '意面&饭类',
          id: 1
        },
        {
          name: '小吃',
          id: 2
        },
        {
          name: '汤&沙拉',
          id: 3
        },
        {
          name: '饮料',
          id: 4
        },
        {
          name: '甜品',
          id: 5
        }
      ],
      numIndex: 0 // 新建一个变量接受首页传过来的id
    }
  },
  created () {
    this.numIndex = this.$route.params.id
  },
  watch: {
    numIndex () {
      if (this.numIndex >= 0) {
        this.current = '' // 找到分类的子元素
        const classify = document.getElementsByClassName('classify_son')
        classify[this.numIndex].classList.add('active')
      }
    }
  },
  mounted () {
    // 使用ref配合refs获取dom元素
    this.$nextTick(() => {
      if (!this.scroll) {
        this.scroll = new BScroll(this.$refs.wrapper, {
          startX: 0,
          click: true,
          scrollX: true,
          scrollY: false
        })
      } else {
        this.scroll.refresh()
      }
    })
  },
  methods: {
    classifyClick (index) {
      // 点击后 去除首页给的active
      const classify = document.getElementsByClassName('classify_son')
      classify[this.numIndex].classList.remove('active')
      // 给current赋值
      this.current = index
      this.$emit('clickIndex', this.current) // 子传父
    }
  }
}
</script>

<style lang='stylus' scoped>
  .classify
    background #fff!important
    display: flex
    overflow-y: hidden
    overflow-x: scroll
    .content
      ul
        display: flex;
        border-bottom 1px solid #f5f5f5
        padding 1px 0
        li
          width 128px
          text-align center
          p
            span
              font-size 26px
              display inline-block
              padding 29px 0
          .active
            border-bottom 6px solid #E0033D
            color #E0033D
    .active p span
      border-bottom 6px solid #E0033D
      color #E0033D
  </style>
